var totalPrice = 0 ;
var proStr;
var address;
var customer;
window.onload = function() {
    var miniCartDisable=true;
    customer = localStorage.getItem('customer');
    //console.log(customer.custName);
    customer = JSON.parse(customer);
    getAddress(customer.accountNo);
    proStr = localStorage.getItem("proInfo");
    proStr = JSON.parse(proStr);
    var parentDiv = document.getElementById("shoppingList");
    for (var i = 0; i < proStr.length; i++) {
        product = proStr[i];
        //console.log(product);
        var dd = document.createElement("dd");//声明第一个div的实例
        dd.className = 'item clearfix';            //设置css样式
        dd.innerHTML = '<div class="item-row"><div class="col col-1"><div class="g-pic">'+
            '<img width="40" height="40" src = "data:image/jpg;base64,' + product.productPhoto +'\">'+
            '</div><div class="g-info"> <a href="#">' +
            product.productName+
            ' </a></div></div><div class="col col-2">'+
            product.salePrice+'元'+'</div> <div class="col col-3">'+
            product.buyAmount+'</div><div class="col col-4">'+
            product.salePrice+'元'+'</div></div>';
        parentDiv.appendChild(dd);
        totalPrice = totalPrice + parseInt(product.salePrice)*parseInt(product.buyAmount);
    }
    checkoutConfig.totalPrice=totalPrice;
    //console.log(totalPrice);
    document.getElementById('allPrice').innerHTML = totalPrice + '元';
    document.getElementById('totalPrice').innerHTML = totalPrice;
}

function getAddress (accountNo){
    //console.log(accountNo);
    $.ajax({
        url: 'customer!getAddress',
        data: {'accountNo': accountNo},
        cache: false,
        async: true,
        traditional: true,
        type: "POST",
        success: function (data) {
            // alert("添加成功！");
            if (data != 'address_null') {
                var rs = eval("(" + data + ")") ;
                var str = ' <dl class="item selected" ><dt><strong class="itemConsignee" id = "custName">'+rs.custName+'</strong>'
           +'<span class="itemTag tag" id = \'tagName\'>'+rs.tagname+'</span> </dt><dd>'
           +' <p class="tel itemTel" id = \'custPhone\'>'+  rs.custPhone    +' </p>'
           +   '  <p class="itemRegion" id = \'province\' >'+rs.province + '省 '+ rs.city + '  ' + rs.region +'</p>'
           +     '<p class="itemStreet" id = \'detailedAddess\'>'+rs.detailedAddress+'</p>'
           +   '  <span class="edit-btn J_editAddr">编辑</span>  </dd>'
           +' <dd style="display:none"> <input type="radio" name="Checkout[address]" class="addressId"  value="10140916720030323">'
           +'</dd> </dl>'     ;
                $('#checkoutAddrList').html(str+'<div class="item use-new-addr"  id="J_useNewAddr" data-state="off">' +
                    '<span class="iconfont icon-add"><img src="images/add_cart.png" /></span>使用新地址</div>');
                address = rs;
              /*  document.getElementById('custName').innerHTML = rs.custName;
                document.getElementById('custPhone').innerHTML = rs.custPhone;*/
                document.getElementById('province').innerHTML = rs.province + '省 '+ rs.city + '市' + rs.region + '区';
                document.getElementById('detailedAddess').innerHTML = rs.detailedAddress;
                document.getElementById('tagName').innerHTML = rs.tagName;
                //localStorage.setItem('customerAddress',rs);
                //        // layer.msg(data.content, {icon: 6});
            } else {
              console.log(data);
              //alert('请添加收货地址！');
             //$('#checkoutAddrList').hide();
                //         //layer.msg(data.content, {icon: 1});
            }
        },
        error: function (data) {
            eval("(" + data + ")");

        },
    });

}
function addAddress(){
    console.log($('#Provinces').val());
    var custAddress = {};
    custAddress.id = 2;
    custAddress.accountNo = customer.accountNo;
    custAddress.custName = $('#Consignee').val();
    custAddress.custPhone = $('#Telephone').val();
    if(!(/^1[34578]\d{9}$/.test($('#Telephone').val()))) {
        alert("手机号码有误，请重填!");
        return ;
    }
        custAddress.city = $('#Citys option:selected').text();
        custAddress.province = $('#Provinces option:selected').text();
        custAddress.region = $('#Countys option:selected').text();
        custAddress.detailedAddress = $('#Street').val();
        custAddress.code = $('#code').val();
        custAddress.tagName = $('#Tag').val();
        var  c = $("#Consignee"), d = $("#Provinces"), e = $("#Citys"), f = $("#Countys"), g = $("#Street"),
            h = $("#Zipcode"), i = $("#Telephone"), j = $("#Tag"), k = /^[1-9]+\d*$/, l = /^\d{6}$/, m = /^1[0-9]{10}$/,
            n = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
            o = /^\d+$/, p = /^[0-9a-zA-Z]+$/, q = /^[a-zA-Z\u4e00-\u9fa5]+$/, r = {}, s = $("#addrState").val();
        if(d.val() ==0 ){alert('请选择省份');return;}
       if(e.val() ==0 ){alert('请选择城市');return;}
         if(f.val() ==0 ){alert('请选择所在区');return;}
       // if (!q.test(t)) { alert( "收货人姓名不正确（只能是英文、汉字）"); return;}
    var C = $.trim(g.val()).replace(/</g, "").replace(/>/g, "").replace(/\//g, "").replace(/\\/g, ""),
        D = g.attr("placeholder");
    if (C === D && (C = ""), !(C.length >= 5 && C.length <= 32)) return ;
        console.log(JSON.stringify(custAddress));
        $.ajax({
            url: 'customer!addAddress',
            data: {'address': JSON.stringify(custAddress)},
            cache: false,
            async: true,
            traditional: true,
            type: "POST",
            success: function (data) {
                // alert(data);
                if (data == "add_success") {
                    alert('地址添加成功！');
                    window.location.reload();
                } else {
                    alert('地址添加失败！');
                }
                /* if (else{}data != 'address_null') {
                     var rs = eval("(" + data + ")") ;
                     address = rs;
                     document.getElementById('custName').innerHTML = rs.custName;
                     document.getElementById('custPhone').innerHTML = rs.custPhone;
                     document.getElementById('province').innerHTML = rs.province + '省 '+ rs.city + '市' + rs.region + '区';
                     document.getElementById('detailedAddess').innerHTML = rs.detailedAddress;
                     document.getElementById('tagName').innerHTML = rs.tagName;
                     //localStorage.setItem('customerAddress',rs);
                     //        // layer.msg(data.content, {icon: 6});
                 } else {
                     console.log(data);
                     alert('请添加收货地址！');
                     $('#address_default').hide();
                     //         //layer.msg(data.content, {icon: 1});
                 }*/
            },
            error: function (data) {
                // eval("(" + data + ")");

            },
        });

}
/*function changeStatus(){

    if($("#delivery").attr("checked")){
        $("#self").attr("checked",true);
        $("#delivery").attr("checked",false);
    };if($("#self").attr("checked")){
        $("#delivery").attr("checked",true);
        $("#self").attr("checked",false);
    };

}*/
function buy() {
    var result = {};
    var orderID = getOrderID();
    var b = $("#checkoutAddrList").find(".selected").length;
    if(b <= 0){alert("请选择收货地址")}else {
        for (var i = 0; i < proStr.length; i++) {
            proStr[i].message = document.getElementById('message').value;
            proStr[i].orderID = orderID;
            proStr[i].buyDate = getDate();
        }
        $.ajax({
            url: 'shoppingCart!buyShopping',
            data: {'list': JSON.stringify(proStr)},
            cache: false,
            async: false,
            traditional: true,
            type: "POST",
            dataType: 'json',
            success: function (data) {
                console.log(data);
                // alert("添加成功！");
                if (data == 'insert_success') {
                    alert("购买成功！");
                    //alert("456");
                    result.feedBack = 'success';
                    result.cusomerName = $('#custName').html();
                    result.phone = $('#custPhone').html();
                    result.orderID = orderID;
                    result.totalPrice = totalPrice;
                    result.address = $('#province').html() + $('#detailedAddess').html();
                    localStorage.setItem('result',JSON.stringify(result));
                    localStorage.removeItem('proInfo');
                    window.location.href = 'buyResult.html';
                    return true;
                    //        // layer.msg(data.content, {icon: 6});
                } else {
                    alert("购买失败！");
                    result.feedBack = 'error';
                    //         //layer.msg(data.content, {icon: 1});
                }
            },
            error: function (data) {
                if (data == 'insert_success') {
                    alert("购买成功！");
                    result.feedBack = 'success';
                    result.cusomerName = $('#custName').html();
                    result.phone = $('#custPhone').html();
                    result.orderID = orderID;
                    result.totalPrice = totalPrice;
                    result.address = $('#province').html() + $('#detailedAddess').html();
                    window.location.href = 'buyResult.html';
                    return true;
                    //        // layer.msg(data.content, {icon: 6});
                } else {
                    alert("购买失败！");
                    result.feedBack = 'error';
                    //         //layer.msg(data.content, {icon: 1});
                }
            }
        });
        localStorage.setItem('result',JSON.stringify(result));
        localStorage.removeItem('proInfo');
    }
}
function getOrderID() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + " " + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    var dateStr = currentdate.replace(/\-/g, "");
      dateStr = dateStr.replace(/\:/g, "").replace(/\s+/g,"");
    return dateStr;
}


function getDate(){
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    return currentdate;
}